<template>
  <PageContainer title="对话管理" description="管理平台上的所有对话记录">
    <div class="admin-page-content chat-manage-page">
      <!-- 搜索表单 -->
      <GlassCard class="search-card">
      <template #header>
        <h3 class="search-title">筛选条件</h3>
      </template>
      <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
        <a-form-item label="消息内容">
          <a-input v-model:value="searchParams.message" placeholder="输入消息内容" class="search-input" />
        </a-form-item>
        <a-form-item label="消息类型">
          <a-select
            v-model:value="searchParams.messageType"
            placeholder="选择消息类型"
            class="search-select"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="user">用户消息</a-select-option>
            <a-select-option value="assistant">AI消息</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="应用ID">
          <a-input v-model:value="searchParams.appId" placeholder="输入应用ID" class="search-input-small" />
        </a-form-item>
        <a-form-item label="用户ID">
          <a-input v-model:value="searchParams.userId" placeholder="输入用户ID" class="search-input-small" />
        </a-form-item>
        <a-form-item>
          <GlassButton type="primary" size="small" html-type="submit" :loading="loading">搜索</GlassButton>
        </a-form-item>
        <a-form-item>
          <GlassButton type="secondary" size="small" @click="doReset">重置</GlassButton>
        </a-form-item>
      </a-form>
    </GlassCard>

    <!-- 表格 -->
    <GlassTable
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      :loading="loading"
      @change="doTableChange"
      :scroll="{ x: 940 }"
      class="chat-table"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'message'">
          <div class="message-text">
            {{ record.message && record.message.length > 50 ? record.message.substring(0, 50) + '...' : record.message }}
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'messageType'">
          <a-tag :color="record.messageType === 'user' ? 'blue' : 'green'">
            {{ record.messageType === 'user' ? '用户消息' : 'AI消息' }}
          </a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ formatTime(record.createTime) }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <GlassButton type="primary" size="small" @click="viewAppChat(record.appId)">
              查看对话
            </GlassButton>
            <a-popconfirm title="确定要删除这条消息吗？" @confirm="deleteMessage(record.id)">
              <GlassButton type="danger" size="small">删除</GlassButton>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </GlassTable>
    </div>
  </PageContainer>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { listAllChatHistoryByPageForAdmin } from '@/api/chatHistoryController'
import { formatTime } from '@/utils/time'
import PageContainer from '@/components/base/PageContainer.vue'
import GlassCard from '@/components/base/GlassCard.vue'
import GlassButton from '@/components/base/GlassButton.vue'
import GlassTable from '@/components/base/GlassTable.vue'

const router = useRouter()

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 100,
    fixed: 'left',
    align: 'center',
  },
  {
    title: '消息内容',
    dataIndex: 'message',
    width: 150,
  },
  {
    title: '消息类型',
    dataIndex: 'messageType',
    width: 100,
    align: 'center',
  },
  {
    title: '应用ID',
    dataIndex: 'appId',
    width: 80,
    align: 'center',
  },
  {
    title: '用户ID',
    dataIndex: 'userId',
    width: 80,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 160,
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
    align: 'center',
  },
]

// 数据
const data = ref<API.ChatHistory[]>([])
const total = ref(0)
const loading = ref(false)

// 搜索条件
const searchParams = reactive<API.ChatHistoryQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await listAllChatHistoryByPageForAdmin({
      ...searchParams,
    })
    if (res.data.data) {
      data.value = res.data.data.records ?? []
      total.value = res.data.data.totalRow ?? 0
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    console.error('获取数据失败：', error)
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

// 表格变化处理
const doTableChange = (page: { current: number; pageSize: number }) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索
const doSearch = () => {
  // 重置页码
  searchParams.pageNum = 1
  fetchData()
}

// 重置
const doReset = () => {
  searchParams.message = ''
  searchParams.messageType = ''
  searchParams.appId = undefined
  searchParams.userId = undefined
  searchParams.pageNum = 1
  fetchData()
}

// 查看应用对话
const viewAppChat = (appId: number | undefined) => {
  if (appId) {
    router.push(`/app/chat/${appId}`)
  }
}

// 删除消息
const deleteMessage = async (id: number | undefined) => {
  if (!id) return

  try {
    // 注意：这里需要后端提供删除对话历史的接口
    // 目前先显示成功，实际实现需要调用删除接口
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } catch (error) {
    console.error('删除失败：', error)
    message.error('删除失败')
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 24px;
}

.search-title {
  margin: 0;
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
  font-weight: 500;
}

.search-form {
  margin-top: 16px;
  flex-wrap: wrap;
  gap: 8px;
}

.search-form .ant-form-item {
  margin-bottom: 16px;
}

.search-form :deep(.ant-form-item-label > label) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.search-form :deep(.ant-input),
.search-form :deep(.ant-select-selector) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  color: #ffffff;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.search-form :deep(.ant-input::placeholder) {
  color: rgba(255, 255, 255, 0.5);
}

.search-form :deep(.ant-input:focus),
.search-form :deep(.ant-select-focused .ant-select-selector) {
  border-color: #60a5fa;
  box-shadow: 0 0 0 2px rgba(96, 165, 250, 0.2);
  background: rgba(255, 255, 255, 0.15);
}

.search-form :deep(.ant-select-arrow) {
  color: rgba(255, 255, 255, 0.6);
}

/* 搜索框和选择器尺寸优化 */
.search-input {
  width: 220px !important;
}

.search-input-small {
  width: 120px !important;
}

.search-select {
  width: 150px !important;
}

.search-form :deep(.ant-form-item) {
  margin-right: 16px;
  margin-bottom: 16px;
}

.admin-page-content {
  max-width: 85%;
  margin: 0 auto;
}

.chat-table {
  min-height: 400px;
}

.message-text {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.type-tag {
  font-size: 12px;
}

/* 自定义滚动条样式 */
:deep(.ant-table-body) {
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
}

:deep(.ant-table-body::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.ant-table-body::-webkit-scrollbar-track) {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

:deep(.ant-table-body::-webkit-scrollbar-thumb) {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

:deep(.ant-table-body::-webkit-scrollbar-thumb:hover) {
  background: rgba(255, 255, 255, 0.5);
}

/* 表格行悬停效果 */
:deep(.ant-table-tbody > tr:hover > td) {
  background: rgba(255, 255, 255, 0.05) !important;
}

:deep(.ant-table-tbody > tr > td) {
  vertical-align: middle;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .search-form .ant-form-item {
    margin-bottom: 8px;
    margin-right: 0;
  }
}

@media (max-width: 768px) {
  .search-form .ant-form-item-label {
    text-align: left;
    padding-bottom: 4px;
  }

  .chat-table {
    font-size: 12px;
  }

  .message-text {
    max-width: 200px;
  }
}

@media (max-width: 480px) {
  .chat-table {
    font-size: 11px;
  }

  .message-text {
    max-width: 150px;
  }
}
</style>
